import { ref, computed, watch, Ref } from 'vue';
import type { TuiMenuProps } from './types';
import { strings } from '../../../';

/**
 * Menu样式管理组合式函数
 * 用于解决Teleport导致的CSS变量作用域问题
 */
export function useMenuStyles(props: TuiMenuProps) {
  // 响应式存储CSS变量
  const cssVars = ref<Record<string, string>>({});

  // 计算CSS变量
  const computedCssVars = computed(() => {
    const styles: Record<string, string> = {};

    // 菜单宽度相关
    styles['--tui-menu-vertical-width'] = strings.ensureUnit(props.verticalWidth || '200px', 'px');
    styles['--tui-menu-vertical-collapse-width'] = strings.ensureUnit(props.verticalCollapseWidth || '56px', 'px');
    styles['--tui-menu-horizontal-height'] = strings.ensureUnit(props.horizontalHeight || '60px', 'px');

    // 颜色相关
    styles['--tui-menu-background-color'] = props.backgroundColor || 'var(--tui-color-white, #ffffff)';
    styles['--tui-menu-text-color'] = props.textColor || 'var(--tui-text-color-primary, #303133)';
    styles['--tui-menu-active-text-color'] = props.activeTextColor || 'var(--tui-text-color-active, #409eff)';
    styles['--tui-menu-hover-background-color'] = props.hoverBackgroundColor || 'var(--tui-color-hover, #f5f7fa)';

    // 偏移量相关
    styles['--tui-menu-popper-offset'] = strings.ensureUnit(props.popperOffset || '6', 'px');
    styles['--tui-menu-popper-offset-x'] = props.popperOffsetX !== undefined
      ? strings.ensureUnit(props.popperOffsetX, 'px')
      : styles['--tui-menu-popper-offset'];
    styles['--tui-menu-popper-offset-y'] = props.popperOffsetY !== undefined
      ? strings.ensureUnit(props.popperOffsetY, 'px')
      : styles['--tui-menu-popper-offset'];

    return styles;
  });

  // 监听props变化，更新CSS变量
  watch(
    computedCssVars,
    (newVars) => {
      cssVars.value = { ...newVars };
    },
    { immediate: true, deep: true }
  );

  /**
   * 应用CSS变量到元素
   * @param element 目标DOM元素
   */
  function applyCssVars(element: HTMLElement | null) {
    if (!element) return;

    Object.entries(cssVars.value).forEach(([key, value]) => {
      element.style.setProperty(key, value);
    });
  }

  /**
   * 获取CSS变量对象，用于直接应用到元素
   */
  function getCssVarsObject(): Record<string, string> {
    return { ...cssVars.value };
  }

  return {
    cssVars,
    computedCssVars,
    applyCssVars,
    getCssVarsObject
  };
}

/**
 * 注入的菜单样式上下文类型
 */
export interface MenuStylesContext {
  cssVars: Ref<Record<string, string>>;
  applyCssVars: (element: HTMLElement | null) => void;
  getCssVarsObject: () => Record<string, string>;
}

// 导出必要的类型
export { type Ref } from 'vue';